package com.itheima.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.controller
 */
@RestController
@RequestMapping("/dfs")
@Slf4j
@Api("分布式文件微服")
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public ResultVo uploadFile(MultipartFile multipartFile){
        // 获取请求的来源
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if(StringUtils.isEmpty(from)){
            throw new LeadNewsException("拒绝上传");
        }
        // 获取源文件名
        String filename = multipartFile.getOriginalFilename();
        log.info("上传文件：{}", filename);
        String ext = StringUtils.getFilenameExtension(filename);
        try {
            // 上传
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(),
                multipartFile.getSize(), ext, null);
            // 文件ID
            String fileId = storePath.getFullPath();
            log.info("上传文件：{} fileId: {}", filename,fileId);
            // 远程调用自媒体微服，添加素材信息
            if(SystemConstants.WEMEDIA_PIC.equals(from)) {
                addWmMaterial(fileId);
            }

            //{url:fileId}
            // 为了页面可以回显图片，要返回完整路径
            ResultVo resultVo = ResultVo.ok(Collections.singletonMap("url", fdfsWebServer.getWebServerUrl()+fileId));
            return resultVo;
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("上传文件失败", e);
        }
        return ResultVo.bizError("上传文件失败");
    }

    /**
     * 远程调用自媒体 添加素材
     * @param fileId
     */
    private void addWmMaterial(String fileId) {
        //1. 构建素材对象
        log.info("添加素材");
        WmMaterial material = new WmMaterial();
        material.setUrl(fileId);
        material.setIsCollection(0);//0：不是收藏
        material.setCreatedTime(LocalDateTime.now());
        material.setType(0);// 0：图片
        material.setUserId(Integer.parseInt(RequestContextUtil.getLoginUserId()));
        //2. 远程调用
        ResultVo result = wmMaterialFeign.add(material);
        //3. 调用失败要报错
        if(!result.isSuccess()){
            throw new LeadNewsException("文件上传，调用自媒体添加素材失败");
        }
        log.info("添加素材成功");
    }


}
